<?php
/**
 * @link https://ym2.cleverstone.top
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

namespace builder\form\util\control\trigger;

use yii\base\BaseObject;
use builder\form\FormTrait;
use yii\base\InvalidArgumentException;

/**
 * 触发条件
 * @author cleverstone
 * @since ym2.0
 */
class Where extends BaseObject
{
    use FormTrait;

    /**
     * @var string 表单分组
     */
    public $formGroup = 'default';

    /**
     * @var string 表单字段
     */
    public $field;

    /**
     * @var string 支持的操作符
     * + == 等于
     * + === 全等于
     * + != 不等于
     * + !== 不全等于
     * + < 小于
     * + <= 小于等于
     * + > 大于
     * + >= 大于等于
     */
    public $op = '==';

    /**
     * @var string|int|float 值
     */
    public $value = '';

    /**
     * 输出JS表达式
     * @return string
     */
    public function toString()
    {
        $scope = '$scope.' . $this->getScope();
        $value = $this->getValue();
        return "{$scope} {$this->op} {$value}";
    }

    /**
     * 获取Angular Scope字段
     * @return string
     */
    public function getScope()
    {
        return $this->combineCtrlScope($this->formGroup, $this->field);
    }

    /**
     * 获取值
     * @return float|int|string
     */
    protected function getValue()
    {
        if (is_string($this->value)) {
            return '"' . $this->value . '"';
        }

        if (is_numeric($this->value)) {
            return $this->value;
        }

        if (is_bool($this->value)) {
            return (int)$this->value;
        }

        if ($this->value === null) {
            return 'undefined';
        }

        throw new InvalidArgumentException('The parameter value must be scalar, but other type is given. ');
    }
}